﻿using System;
using System.Linq;
using System.Reflection;

namespace EasyLib.Extensions
{
    [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
    public class AttachDataAttribute : Attribute
    {
        public AttachDataAttribute(object key, object value)
        {
            this.Key = key;
            this.Value = value;
        }

        public object Key { get; private set; }

        public object Value { get; private set; }
    }

    public static class AttachDataExtensions
    {
        public static object GetAttachedData(
            this ICustomAttributeProvider provider, object key)
        {
            var attributes = (AttachDataAttribute[])provider.GetCustomAttributes(
                typeof(AttachDataAttribute), false);
            return attributes.First(a => a.Key.Equals(key)).Value;
        }

        public static T GetAttachedData<T>(
            this ICustomAttributeProvider provider, object key)
        {
            return (T)provider.GetAttachedData(key);
        }

        public static object GetAttachedData(this Enum value, object key)
        {
            return value.GetType().GetField(value.ToString()).GetAttachedData(key);
        }

        public static T GetAttachedData<T>(this Enum value, object key)
        {
            return (T)value.GetAttachedData(key);
        }
    }

    public enum AgeRange
    {
        [AttachData(AgeRangeAttachData.Text, "18岁及以下")]
        LessThan18,

        [AttachData(AgeRangeAttachData.Text, "19至29岁")]
        From19To29,

        [AttachData(AgeRangeAttachData.Text, "30岁及以上")]
        Above29
    }

    public enum AgeRangeAttachData
    {
        Text
    }

    public static class AgeRangeExtensions
    {
        //usage: AgeRange.From19To29.GetText()
        public static string GetText(this AgeRange range)
        {
            return range.GetAttachedData<string>(AgeRangeAttachData.Text);
        }
    }

}
